#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Rust知识解释智能体Web应用启动脚本
"""

import os
import sys
import subprocess
from pathlib import Path

def check_dependencies():
    """检查依赖包是否已安装"""
    required_packages = ['flask', 'openai']
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package)
        except ImportError:
            missing_packages.append(package)
    
    if missing_packages:
        print(f"❌ 缺少依赖包: {', '.join(missing_packages)}")
        print("请运行以下命令安装依赖:")
        print("pip install -r requirements.txt")
        return False
    
    return True

def check_files():
    """检查必要文件是否存在"""
    required_files = [
        'app.py',
        'main.py',
        'question_classifier.py',
        'semantic_retriever.py',
        'answer_generator.py',
        'multimodal_renderer.py',
        'context_manager.py',
        'templates/index.html',
        'static/css/style.css',
        'static/js/app.js'
    ]
    
    missing_files = []
    for file_path in required_files:
        if not Path(file_path).exists():
            missing_files.append(file_path)
    
    if missing_files:
        print(f"❌ 缺少文件: {', '.join(missing_files)}")
        return False
    
    return True

def create_directories():
    """创建必要的目录"""
    directories = ['static/css', 'static/js', 'templates']
    for directory in directories:
        Path(directory).mkdir(parents=True, exist_ok=True)

def main():
    """主函数"""
    print("🚀 Rust知识解释智能体Web应用启动器")
    print("=" * 50)
    
    # 检查依赖
    print("📦 检查依赖包...")
    if not check_dependencies():
        sys.exit(1)
    print("✅ 依赖包检查通过")
    
    # 检查文件
    print("📁 检查文件完整性...")
    if not check_files():
        print("❌ 文件检查失败，请确保所有文件都存在")
        sys.exit(1)
    print("✅ 文件检查通过")
    
    # 创建目录
    print("📂 创建必要目录...")
    create_directories()
    print("✅ 目录创建完成")
    
    # 启动应用
    print("\n🎯 启动Web应用...")
    print("📱 访问地址: http://localhost:5000")
    print("🔧 API状态: http://localhost:5000/api/status")
    print("⏹️  按 Ctrl+C 停止服务")
    print("=" * 50)
    
    try:
        # 导入并运行Flask应用
        from app import app
        app.run(debug=True, host='0.0.0.0', port=5000)
    except KeyboardInterrupt:
        print("\n👋 服务已停止")
    except Exception as e:
        print(f"❌ 启动失败: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main() 